import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:flutter_audio_recorder/flutter_audio_recorder.dart';
import 'package:intl/intl.dart';
import 'package:file/local.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:audioplayers/audioplayers.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  FlutterBlue flutterBlue = FlutterBlue.instance;
  List devices = [];
  Recording recording;
  var recorder;
  static LocalFileSystem localFileSystem = LocalFileSystem();
  Directory appDocDirectory;
  Recording _current;
  RecordingStatus _currentStatus = RecordingStatus.Unset;
  BluetoothDevice connectedDevice;
//        io.Directory appDocDirectory = await getApplicationDocumentsDirectory();


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    FlutterAudioRecorder.hasPermissions;
    startScan();

// Stop scanning
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Stack(
        alignment: Alignment.center,
        children: <Widget>[

          Container(
            child: ListView.builder(
              itemBuilder: (context, i) {
                var device = devices[i].device;
                var advertisementData = devices[i].advertisementData;
                return GestureDetector(
                  onTap: (){
                    device.conncet().then((){
                      setState(() {
                        connectedDevice = device;
                      });
                    });

                  },
                  child: Container(
                    child: ListTile(
                      title: device.name,
                    ),
                  ),
                );
              },
              itemCount: devices.length,
            ),
          ),
          Positioned(
              bottom: 92,
              child: Container(
                child:_buildText(),
              )
          ),
          Positioned(
            bottom: 10,
            child:Container(
              width:  MediaQuery
                  .of(context)
                  .size
                  .width,
              height: 72,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                 GestureDetector(
                   onLongPressStart: (detail){
                     startRecord(1);
                   },
                   onLongPressUp: (){
                     stopRecord(1);
                   },
                   child:  Container(
                     height: 72,
                     child: Column(
                       children: <Widget>[
                         CupertinoButton(
                             color: Colors.blue,
                             child: Icon(
                               Icons.record_voice_over,
                               color: Colors.white,
                             ),
                         ),
                         Text('录音按键1')
                       ],
                     ),
                   ),
                 ),
                  GestureDetector(
                      onLongPressStart: (detail){
                        startRecord(2);
                      },
                      onLongPressUp: (){
                        stopRecord(2);
                      },
                      child: Container(
                      height: 72,
                      child: Column(
                        children: <Widget>[
                          CupertinoButton(
                              color: Colors.blue,
                              child: Icon(
                                Icons.record_voice_over,
                                color: Colors.white,
                              ),
                              onPressed: () {

                              }
                          ),
                          Text('录音按键2')
                        ],
                      ),
                    )
                  )
                ],
                )
            )
          )
        ],
      ),
    );
  }
  void startScan() {
    flutterBlue.startScan(timeout: Duration(seconds: 4));
    // Listen to scan results
    var subscription = flutterBlue.scanResults.listen((scanResult) {
      // do something with scan result
      List _devices = [];
      for(var i=0;i<scanResult.length;i++) {
        var device = scanResult[i].device;
        var advertisementData = scanResult[i].advertisementData;
        if(device.name != '' && advertisementData.connectable) {
          _devices.add(scanResult[i]);
        }
        print('${advertisementData.localName} found! rssi: ${scanResult[i].rssi}');
      }
      setState(() {
        devices = _devices;
      });
      return scanResult;
    });
  }

  void startRecord(int index) async {
    if(connectedDevice == null) {
      return;
    }
    var formatter = new DateFormat('yyyy_MM_dd_HH_mm_ssms');
    var now = DateTime.now();
    print(formatter.format(now));
    if (Platform.isIOS) {
      appDocDirectory = await getApplicationDocumentsDirectory();
    } else {
      appDocDirectory = await getExternalStorageDirectory();
    }
    setState(() {
      recorder = FlutterAudioRecorder(appDocDirectory.path + index.toString() + "$now.wav"); // .wav .aac .m4a
    });
    await recorder.initialized;
    await recorder.start();
   var _recording =  await recorder.current(channel: 0);
    setState(() {
      recording = _recording;
      _currentStatus = _recording.status;
      print(_currentStatus);
    });
  }

  discoverService() async {
    List<BluetoothService> services = await connectedDevice.discoverServices();
    services.forEach((service) {
      // do something with service
    });
    return services;
  }


  void stopRecord(int index) async {
    var result = await recorder.stop();
    print("Stop recording: ${result.path}");
    print("Stop recording: ${result.duration}");
    File file = localFileSystem.file(result.path);
    onPlayAudio(result.path);
    setState(() {
      recording = result;
      _currentStatus = recording.status;
    });
  }

  void onPlayAudio(path) async {
    AudioPlayer audioPlayer = AudioPlayer();
   var result = await audioPlayer.play(path, isLocal: true);
   print(result);
  }

  Widget _buildText() {
    var text = "";
    switch (_currentStatus) {
      case RecordingStatus.Initialized:
        {
          text = '录音初始化';
          break;
        }
      case RecordingStatus.Recording:
        {
          text = '录音中';
          break;
        }
      case RecordingStatus.Paused:
        {
          text = '录音暂停';
          break;
        }
      case RecordingStatus.Stopped:
        {
          text = '录音完毕';
          break;
        }
      default:
        break;
    }
    return Text(text, style: TextStyle(color: Colors.blue));
  }
}
